from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from myapp.models import Picture
from datetime import datetime
from PIL import Image
import time
import os
# Create your views here.


def home(request):
    """
    首页
    """
    return render(request, "myapp/home.html")


def index(request, pIndex):
    """
    图片列表
    """
    try:
        list = Picture.objects.filter(isDelete=False)
        p = Paginator(list, 10)
        if pIndex == '':
            pIndex = '1'
        pIndex = int(pIndex)
        pagedList = p.page(pIndex)
        plist = p.page_range

        context = {"picList": pagedList, 'plist': plist, 'pIndex': pIndex}
        return render(request, "myapp/index.html", context)
    except:
        return HttpResponse("没有找到对应的信息！")


def addPicture(request):
    """
    新增图片表单
    """
    return render(request, "myapp/add.html")


def insertPicture(request):
    """
    新增图片到数据库
    """
    try:
        pic = Picture()
        pic.title = request.POST["title"]
        pic.upload_date = datetime.now()
        # 图片上传
        myfile = request.FILES.get("pic", None)
        if not myfile:
            return HttpResponse("没有上传文件信息")
        filename = str(time.time())+"."+myfile.name.split('.').pop()
        destination = open("./static/myapp/"+filename, "wb+")
        for chunk in myfile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()
        pic.pic_url = "/static/myapp/"+filename
        # 执行图片缩放
        im = Image.open("./static/myapp/"+filename)
        # 缩放到75*75(缩放后的宽高比例不变):
        im.thumbnail((75, 75))
        # 把缩放后的图像用jpeg格式保存:
        im.save("./static/myapp/s_"+filename, None)
        pic.s_pic_url = "/static/myapp/s_"+filename

        pic.save()
        context = {"info": "添加成功！"}
    except:
        context = {"info": "添加失败！"}
    return render(request, "myapp/info.html", context)


def editPicture(request, picId):
    """
    更新图片
    """
    try:
        pic = Picture.objects.get(id=picId)
        context = {"pic": pic}
        return render(request, "myapp/edit.html", context)
    except:
        context = {"info": "要编辑的信息不存在！"}
        return render(request, "myapp/info.html", context)


def updatePicture(request):
    """
    更新图片方法
    """
    try:
        pic = Picture.objects.get(id=request.POST["id"])
        pic.title = request.POST["title"]

        myfile = request.FILES.get("picFile", None)
        if myfile:
            # 删除原先的图片然后上传新的
            if os.path.exists("."+pic.pic_url):
                os.remove("."+pic.pic_url)
            if os.path.exists("."+pic.s_pic_url):
                os.remove("."+pic.s_pic_url)

            filename = str(time.time())+"."+myfile.name.split('.').pop()
            destination = open("./static/myapp/"+filename, "wb+")
            for chunk in myfile.chunks():      # 分块写入文件
                destination.write(chunk)
            destination.close()
            pic.pic_url = "/static/myapp/"+filename
            # 执行图片缩放
            im = Image.open("./static/myapp/"+filename)
            # 缩放到75*75(缩放后的宽高比例不变):
            im.thumbnail((75, 75))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/myapp/s_"+filename, None)
            pic.s_pic_url = "/static/myapp/s_"+filename

            pic.upload_date = datetime.now()  # 上传时间

        pic.save()
        context = {"info": "更新成功！"}
    except:
        context = {"info": "更新失败！"}
    return render(request, "myapp/info.html", context)


def deletePicture(request, picId):
    """
    删除图片
    """
    try:
        pic = Picture.objects.get(id=picId)
        pic.isDelete = True
        # 删除图片和缩略图
        if os.path.exists("."+pic.pic_url):
            os.remove("."+pic.pic_url)
        if os.path.exists("."+pic.s_pic_url):
            os.remove("."+pic.s_pic_url)
        pic.save()
        context = {"info": "删除成功！"}
    except:
        context = {"info": "删除失败！"}
    return render(request, "myapp/info.html", context)
